<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" clearable placeholder="请选择项目">
          <el-option v-for="(item, index) in projectList" :key="index" :label="item.name"
            :value="parseInt(item.id)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" clearable placeholder="请选择类型">
          <el-option v-for="dict in dict.type.moe_work_order_type" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择状态">
          <el-option v-for="dict in dict.type.moe_work_order_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-has-permi="['system:order:add']" icon="el-icon-plus" plain size="mini" type="primary"
          @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-has-permi="['system:order:remove']" :disabled="multiple" icon="el-icon-delete" plain size="mini"
          type="danger" @click="handleDelete">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-has-permi="['system:order:export']" icon="el-icon-download" plain size="mini" type="warning"
          @click="handleExport">导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="工单ID" prop="id" />
      <el-table-column align="center" label="项目" prop="projectName">
      </el-table-column>
      <el-table-column align="center" label="申请理由" prop="message" />
      <el-table-column align="center" label="类型" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.moe_work_order_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.moe_work_order_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="工单信息" prop="status">
        <template slot-scope="scope">
          <el-button v-has-permi="['system:project:query']" icon="el-icon-view" size="mini" type="text"
            @click="getInfo(scope.row)">详情
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="备注" prop="remark" />
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-has-permi="['system:order:edit']" icon="el-icon-edit" size="mini" type="text"
            @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-has-permi="['system:order:remove']" icon="el-icon-delete" size="mini" type="text"
            @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审批" prop="status" v-has-permi="['system:order:business']">
        <template slot-scope="scope">
          <el-row style="display: flex; justify-content: space-evenly;">
            <div title="验收">
              <el-button v-has-permi="['system:order:business']" circle icon="el-icon-check" size="mini" type="success"
                @click="agreeOrder(scope.row)" />
            </div>
            <div title="驳回">
              <el-button v-has-permi="['system:order:business']" circle icon="el-icon-refresh-left" size="mini"
                type="danger" @click="rejectOrder(scope.row)" />
            </div>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total"
      @pagination="getList" />

    <!-- 添加或修改工单管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目" :disabled="isUpdate">
            <el-option v-for="(item, index) in projectList" :key="index" :label="item.name"
              :value="parseInt(item.id)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="接收者" prop="receiverId">
          <el-select v-model="form.receiverId" placeholder="请选择接收者" :disabled="isUpdate">
            <el-option v-for="user in userList" :key="user.userId" :label="user.nickName"
              :value="parseInt(user.userId)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型" :disabled="isUpdate">
            <el-option v-for="dict in dict.type.moe_work_order_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-row v-if="form.type === '0'">
          <el-form-item label="初始开始时间" prop="projectStartTime">
            <el-date-picker v-model="currentProject.startTime" :disabled="isUpdate" clearable placeholder="请选择初始开始时间"
              type="date" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="初始结束时间" prop="projectEndTime">
            <el-date-picker v-model="currentProject.endTime" :disabled="isUpdate" clearable placeholder="请选择初始结束时间"
              type="date" value-format="yyyy-MM-dd">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="期望结束时间" prop="projectNewEndTime">
            <el-date-picker v-model="form.projectNewEndTime" clearable placeholder="请选择期望结束时间" type="date"
              value-format="yyyy-MM-dd" :disabled="isUpdate" :picker-options="checkPicker">
            </el-date-picker>
          </el-form-item>
        </el-row>
        <el-row v-if="form.type === '1'">
          <el-form-item label="初始资金" prop="projectFunding">
            <el-input v-model="form.projectFunding" placeholder="请输入初始资金" :disabled="isUpdate" />
          </el-form-item>
          <el-form-item label="扩充资金" prop="increaseFunding">
            <el-input-number v-model="form.increaseFunding" placeholder="请输入扩充资金" :min="0" :disabled="isUpdate" />
          </el-form-item>
        </el-row>
        <el-form-item label="补充附件" prop="file">
          <file-upload v-model="form.file" />
        </el-form-item>
        <el-form-item label="申请理由" prop="message">
          <el-input v-model="form.message" placeholder="请输入申请理由" type="textarea" :disabled="isUpdate" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" :disabled="isUpdate" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{ this.confirm }}</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { addOrder, delOrder, getOrder, listOrder, updateOrder } from "@/api/system/order";
import { getProject, listProject } from '@/api/system/project'
import { getFundInfo } from "@/api/system/fund";
import { listUserByRole } from "@/api/system/user";

export default {
  name: "Order",
  dicts: ['moe_work_order_type', 'moe_work_order_status'],
  data () {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 当前用户id
      currentUserId: null,
      // 工单管理表格数据
      orderList: [],
      // 项目表格数据
      projectList: [],
      // 当前选中项目工单
      // 用户单位数据
      userList: [],
      currentProject: {},
      // 弹出层标题
      title: "",
      // 弹出层确认词
      confirm: '同意',
      // 是否显示弹出层
      open: false,
      isUpdate: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        type: null,
        status: null,
      },
      queryUserListByRoleParams: {
        roleId: 10
      },
      // 项目总资金
      projectTotalFund: null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        receiverId: [
          { required: true, message: "接收者不能为空", trigger: "change" }
        ],
        projectId: [
          { required: true, message: "项目不能为空", trigger: "change" }
        ],
        message: [
          { required: true, message: "申请理由不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
      },
      checkPicker: {
        disabledDate: (time) => {
          return time.getTime() < new Date(this.currentProject.endTime).getTime()
        }
      },
    };
  },
  created () {
    this.getList();
    this.getProject();
    this.getUserList();;
    this.currentUserId = localStorage.getItem('userId')
  },
  watch: {
    'form.projectId': {
      async handler (newVal, oldVal) {
        if (newVal != null || newVal != undefined) {
          this.form.projectId = newVal
          await this.getProjectInfo()
          let response = await getFundInfo({
            projectId: this.form.projectId,
            taskId: 0
          })
          this.form.projectFunding = response.data.totalFunding
        }
      },
    },
  },
  methods: {
    /** 查询工单管理列表 */
    getList () {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
      });
      this.loading = false;
    },
    /** 查询项目列表 */
    getProject () {
      this.loading = true;
      listProject().then(response => {
        this.projectList = response.rows
      })
      this.loading = false;
    },
    // 同意工单
    agreeOrder (row) {

      if (row.status === "0" || row.status === "1") {
        this.$message('该工单已处理')
        return
      }
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.form.status = '0';
        this.open = true;
        this.title = '工单审批';
        this.confirm = "同意"
      });
    },
    // 驳回工单
    rejectOrder (row) {
      if (row.status === "0" || row.status === "1") {
        this.$message('该工单已处理')
        return
      }
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.form = response.data;
        this.form.status = '1';
        this.open = true;
        this.title = "工单驳回";
        this.confirm = "驳回"
      });
    },
    // 任务详情
    getInfo (row) {
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {
        this.isUpdate = true
        this.form = response.data;
        this.form.status = '2';
        this.open = true;
        this.title = "更新工单";
        this.confirm = "更新"
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.isUpdate = false
      console.log(this.isUpdate);
      if (row.status === "0") {
        this.$message('该工单已处理')
        return
      }
      this.reset();
      const id = row.id || this.ids
      getOrder(id).then(response => {

        this.form = response.data;
        this.form.status = '2';
        this.open = true;
        this.title = "更新工单";
        this.confirm = "更新"
      });
    },
    /** 查询项目详情信息 */
    async getProjectInfo () {
      let response = await getProject(this.form.projectId)
      this.currentProject = response.data
      this.form.projectStartTime = this.currentProject.startTime
      this.form.projectEndTime = this.currentProject.endTime
    },
    /** 查询角色是项目管理员的用户列表 */
    getUserList () {
      this.loading = true;
      listUserByRole(this.queryUserListByRoleParams).then(response => {
        this.userList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        senderId: null,
        receiverId: null,
        projectId: null,
        message: null,
        type: null,
        projectStartTime: null,
        projectEndTime: null,
        projectNewEndTime: null,
        projectFunding: null,
        increaseFunding: null,
        status: null,
        file: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.isUpdate = false
      this.open = true;
      this.title = "添加工单";
    },

    /** 提交按钮 */
    submitForm () {
      if (this.isUpdate) {
        this.open = false;
        return
      }
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateOrder(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOrder(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除工单编号为"' + ids + '"的数据项？').then(function () {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('system/order/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
